<template>
    <div :style="carStyle">
        <div v-if="!showContent" class="defaultText">请在右侧配置数据</div>
        <template v-else>
            <div class="lineTitle" v-if="obj.isShowTitle" :style="titleStyle">{{ obj.title }}</div>
        </template>
        <div class="chart" ref="constat" :style="canvasStyle" @click="gotoUrl(obj)"></div>
    </div>
</template>

<script>
import * as echarts from 'echarts';
// import { oneLoad, boardOneLoad } from '@/api/share'

export default {
    Name: "Gauge",
    components: {
        echarts
    },
    props: {
        obj: Object,
        discount: Number,
        isReload: {
            type: Boolean,
            default: false
        },
        isEdit: {
            type: Boolean,
            default: false,
        },
        gotoUrl: Function,
        getTableValue: Function,
    },
    data() {
        return {
            showContent: true,
            carStyle: {},
            titleStyle: {},
            canvasStyle: {
                width: "100%",
                height: "100%"
            },
            chart: undefined,
            // 用于比对数据是否修改
            dataStr: "",
            timer: null,
            dataValue: 0,
            filterForm: {},
        }
    },
    mounted() {
        this.setStyle();

        this.$nextTick(function () {
            this.reloadInfo();
        })

        this.dataStr = JSON.stringify(this.obj.tableData);

        // 页面变化调整尺寸
        var self = this;
        window.addEventListener('resize', function () {
            if (self.chart) {
                self.chart.resize();
            }
        }, true);
    },
    beforeDestroy() {
        if (!this.chart) {
            return
        }
        this.chart.dispose()
        this.chart = null
        clearInterval(this.timer)
    },
    methods: {
        // 除样式外其他数据更改调用刷新
        reloadInfo() {
            if (this.chart) {
                this.chart.dispose()
            }
            var constat = this.$refs.constat;
            this.chart = echarts.init(constat);

            var timeSize = 60;
            if (this.obj.tableData.reloadTime) {
                timeSize = this.obj.tableData.reloadTime;
            }

            if (this.obj.tableData.type == 1) {
                // 刷新时间兼容处理
                if (timeSize < 60) {
                    timeSize = 60;
                }
            }

            clearInterval(this.timer);
            this.getFirstData();

            if (this.isReload) {
                this.timer = setInterval(() => {
                    this.getLineData();
                }, timeSize * 1000);
            }
        },
        setStyle() {
            var style = this.obj.style;

            var backgroundColor = "";
            var backgroundImage = "";
            // 背景颜色
            if (style.backgroundImage.length) {
                backgroundImage = `url(${style.backgroundImage}`;
            } else if (style.backgroundColor.length > 0) {
                backgroundColor = style.backgroundColor;
            } else {
                backgroundColor = "#04142b";
            }

            var boxShadow = "";
            if (style.boxShadow) {
                boxShadow = `${style.boxShadow.h}px ${style.boxShadow.v}px ${style.boxShadow.blur}px ${style.boxShadow.spreed}px ${style.boxShadow.color}`
            }

            this.carStyle = {
                boxShadow,
                width: "100%",
                height: "100%",
                display: "flex",
                backgroundSize: "100% 100%",
                borderStyle: "solid",
                backgroundImage,
                backgroundColor,
                color: style.color,
                fontSize: style.fontSize + "px",
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
                borderColor: style.borderColor,
                borderWidth: style.borderWidth + "px",
                borderRadius: style.borderRadius + "px",
                fontWeight: style.fontWeight,
                fontStyle: style.fontStyle,
            }

            // #region 新的背景颜色

            if (this.obj.style.bgcolorType == "image") {
                this.carStyle.backgroundImage = backgroundImage;
            } else if (this.obj.style.bgcolorType == "gradient") {
                if (this.obj.style.gradient.isRadial) {
                    this.carStyle.backgroundImage = `radial-gradient(${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                } else {
                    this.carStyle.backgroundImage = `linear-gradient(${this.obj.style.gradient.fontAngle}deg, ${this.obj.style.gradient.colorStart}, ${this.obj.style.gradient.colorEnd})`;
                }
            } else {
                this.carStyle.backgroundColor = backgroundColor;
            }

            // #endregion

            this.titleStyle = {
                justifyContent: style.justifyContent,
                alignItems: style.alignItems,
            }

            // 标题隐藏显示
            var isShowTitle = this.obj.isShowTitle ? true : false;
            var echarHeight = style.height;
            var echarMarginTop = 0;
            if (isShowTitle) {
                echarHeight = style.height - style.fontSize - style.borderWidth * 2;
                echarMarginTop = style.fontSize + "px";
            }

            this.canvasStyle = {
                marginTop: echarMarginTop,
                width: "100%",
                height: echarHeight + "px",
            }

            if (this.chart) {
                this.chart.resize({
                    width: style.width,
                    height: echarHeight,
                });
            }
        },
        setOptions() {
            var value = this.dataValue;
            // this.chart.clear()

            var maxValue = 0;
            var color = "#333333";
            if (this.obj.tableData.color) {
                color = this.obj.tableData.color;
            }

            var textStyle = {
                fontSize: '52px', //文本字号,
                color: "#fff",
                fontWeight: '',
                fontStyle: ''
            }
            if (this.obj.tableData.fontSize) {
                textStyle.fontSize = this.obj.tableData.fontSize + "px";
            }
            if (this.obj.tableData.fontColor) {
                textStyle.color = this.obj.tableData.fontColor;
            }
            if (this.obj.tableData.fontWeight) {
                textStyle.fontWeight = this.obj.tableData.fontWeight;
            }
            if (this.obj.tableData.fontStyle) {
                textStyle.fontStyle = this.obj.tableData.fontStyle;
            }

            // if (this.obj.tableData.statusList.length) {
            //     this.obj.tableData.statusList.forEach(e => {
            //         if (e.value && value >= e.value) {
            //             valColor = e.color;
            //         }
            //     })
            // }
            maxValue = this.obj.tableData.statusList[this.obj.tableData.statusList.length - 1].value1;
            var minValue = this.obj.tableData.statusList[0].value;
            var gaugeColors = [];
            var statusData = [];
            var offsetValue = [];
            statusData.push(minValue)
            this.obj.tableData.statusList.forEach(e => {
                gaugeColors.push([e.value1 / maxValue, e.color]);
                statusData.push(Number(e.value1))
                offsetValue.push({ offset: e.value1 / maxValue, color: e.color });
            })

            // 计算刻度的宽度
            var gugeWidth = 20;
            var kdsize = -55;
            var showsize = true;
            if (this.obj.style.width < 400) {
                gugeWidth = this.obj.style.width / 20;
                kdsize = -45;
            }
            if (this.obj.style.width < 300) {
                showsize = false;
            }

            // console.log(statusData);
            // gaugeColors.push([1, '#7CFFB2']);
            // 带刻度
            if (this.obj.tableData.styleTemplate == 1) {
                var ruler = statusData.sort((a, b) => a - b);
                let chartMaxVal = maxValue; //仪表盘对应0--100的最大刻度，越大越精确
                let unitStep = chartMaxVal / (ruler.length - 1);

                let getGaugeData = (value) => {
                    if (value <= ruler[0]) return 0;
                    for (let i = 1; i < ruler.length; i++) {
                        if (value <= ruler[i]) {
                            let startVal = unitStep * (i - 1);
                            let rulerSpan = ruler[i] - ruler[i - 1];
                            let lastRuler = ruler[i - 1];
                            let ret = startVal + ((value - lastRuler) / rulerSpan) * unitStep;
                            return Math.round(ret);
                        }
                    }
                    return chartMaxVal;
                };

                let gaugeData = getGaugeData(value);

                let option = {
                    series: [
                        {
                            name: 'test speed',
                            type: 'gauge',
                            radius: '80%',
                            splitNumber: ruler.length - 1, //仪表盘平均分配分段刻度
                            min: 0,
                            max: maxValue,
                            // splitNumber: maxValue,
                            axisLine: {
                                lineStyle: {
                                    width: 25,
                                    color: gaugeColors
                                },
                            },
                            pointer: {
                                itemStyle: {
                                    color: 'auto',
                                },
                            },
                            splitLine: {
                                distance: -25,
                                length: 25,
                                lineStyle: {
                                    color: '#fff',
                                    width: 4,
                                },
                            },
                            axisTick: {
                                distance: -25,
                                length: 8,
                                lineStyle: {
                                    color: '#fff',
                                    width: 2,
                                },
                            },
                            axisLabel: {
                                show: false,
                                color: 'auto',
                                distance: 40,
                                fontSize: 16,
                                //仪表盘刻度设置
                                formatter: getGaugeData
                            },
                            detail: {
                                // fontSize: 14,
                                formatter: (value1) => {
                                    // return "123"
                                    // return `${value}`;
                                    return value
                                },
                                offsetCenter: [0, '70%'],
                                // valueAnimation: true,
                                // color: 'auto',
                                fontSize: textStyle.fontSize,
                                fontWeight: textStyle.fontWeight,
                                fontStyle: textStyle.fontStyle,
                                // offsetCenter: [0, '17%'],
                                valueAnimation: true,
                                color: textStyle.color,
                            },
                            data: [
                                {
                                    value: gaugeData,
                                },
                            ],
                        },
                    ],
                };

                this.chart.setOption(option);
            }
            else if (this.obj.tableData.styleTemplate == 2) {
                var dataArr = [value];
                var center_1 = ['50%', '50%'];
                var radius_1 = '80%';
                // var color_offset_0 = '#19fdab';
                // var color_offset_1 = '#d0ff19';
                // var color_offset_2 = '#ff4026';
                var line_width = '20';
                var anchor_color = '#0e1327';
                var anchor_size = 10;
                var pointer_length = '90%';
                var pointer_width = 16;
                var pointer_offsetCenter = [0, '5%'];
                var pointer_color_offset_0 = '#FEAD54';
                var pointer_color_offset_1 = '#0e1327';
                // var detail_color = 'red';
                var option = {
                    series: [
                        {
                            data: dataArr,
                            name: '最外层',
                            type: 'gauge',
                            roundCap: true,
                            radius: radius_1,
                            center: center_1,
                            splitNumber: 0, //刻度数量
                            startAngle: 225,
                            endAngle: -45,
                            z: 4,
                            zlevel: 0,
                            axisLine: {
                                show: true,
                                roundCap: true,
                                lineStyle: {
                                    // 轴线样式
                                    width: line_width, // 宽度
                                    color: [
                                        [
                                            1,
                                            new echarts.graphic.LinearGradient(0, 0, 1, 0, offsetValue),
                                        ],
                                    ],
                                },
                            },
                            //分隔线样式
                            splitLine: {
                                show: true,
                            },
                            axisLabel: {
                                show: false,
                            },
                            axisTick: {
                                show: true,
                            },
                            anchor: {
                                show: true,
                                size: anchor_size,
                                showAbove: true,
                                itemStyle: {
                                    color: anchor_color,
                                },
                            },
                            // pointer: {
                            //     icon:
                            //         'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
                            //     show: true,
                            //     length: pointer_length,
                            //     width: pointer_width,
                            //     offsetCenter: pointer_offsetCenter,
                            //     itemStyle: {
                            //         color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                            //             {
                            //                 offset: 0,
                            //                 color: pointer_color_offset_0,
                            //             },
                            //             {
                            //                 offset: 1,
                            //                 color: pointer_color_offset_1,
                            //             },
                            //         ]),
                            //     },
                            // },
                            detail: {
                                fontSize: textStyle.fontSize,
                                fontWeight: textStyle.fontWeight,
                                fontStyle: textStyle.fontStyle,
                                valueAnimation: true,
                                formatter: function (value3) {
                                    // alert(value)
                                    return value;
                                },
                                color: textStyle.color,
                                fontFamily: 'D-DIN',
                                offsetCenter: [0, '75%'],
                            },
                        },
                        {
                            name: '第二层刻度',
                            type: 'gauge',
                            center: ['50%', '50%'],
                            radius: '75%',
                            // distance : 100,
                            startAngle: 225,
                            endAngle: -45,
                            axisLine: {
                                show: false,
                            }, //仪表盘轴线
                            axisLabel: {
                                show: false,
                                color: '#FFFFFF',
                                distance: 20,
                            }, //刻度标签。
                            axisTick: {
                                show: true,
                                splitNumber: 5,
                                lineStyle: {
                                    color: '#f40', //用颜色渐变函数不起作用
                                    width: 1,
                                },
                                distance: 20,
                                length: 15,
                            },
                            splitLine: {
                                show: false,
                            },
                            detail: {
                                show: false,
                            },
                            pointer: {
                                show: false,
                            },
                        },
                        {
                            name: '内部细刻度',
                            type: 'gauge',
                            center: ['50%', '50%'],
                            radius: '55%',
                            startAngle: 225,
                            endAngle: -45,
                            axisLine: {
                                show: true,
                                lineStyle: {
                                    width: 1,
                                    color: [
                                        [
                                            1,
                                            new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                                {
                                                    offset: 0,
                                                    color: '#224570',
                                                },
                                                {
                                                    offset: 1,
                                                    color: '#224570',
                                                },
                                            ]),
                                        ],
                                    ],
                                },
                            }, //仪表盘轴线
                            axisTick: {
                                show: false,
                            },
                            //刻度线文字
                            axisLabel: {
                                show: false,
                            },
                            splitLine: {
                                show: false,
                            },
                            detail: {
                                show: false,
                            },
                            pointer: {
                                show: false,
                            },
                        },
                    ],
                };

                this.chart.setOption(option);
            }
            else if (this.obj.tableData.styleTemplate == 3) {
                var option = {
                    series: [{
                        tooltip: {
                            show: false
                        },
                        type: 'gauge',
                        radius: '92%',
                        center: ['50%', '80%'],
                        startAngle: 180,
                        endAngle: 0,
                        detail: {
                            show: false
                        },
                        axisLine: {
                            lineStyle: {
                                width: 8,
                                color: gaugeColors
                            }
                        },
                        axisLabel: {
                            show: false
                        },
                        axisTick: {
                            show: false,
                        },
                        splitLine: {
                            show: false,
                        },
                    }, {
                        type: 'gauge',
                        radius: '72%',
                        min: 0,
                        max: maxValue,
                        center: ['50%', '80%'],
                        data: [{
                            value: value,
                        }],
                        splitNumber: 10,
                        startAngle: 180,
                        endAngle: 0,
                        // title: {
                        //     offsetCenter: ['0', '-60%'],
                        //     fontSize: 40
                        // },
                        detail: {
                            formatter: function (value2) {
                                return value;
                            },
                            // fontSize: 50,
                            // color: '#fff',
                            offsetCenter: ['0%', '-45%'],
                            fontSize: textStyle.fontSize,
                            fontWeight: textStyle.fontWeight,
                            fontStyle: textStyle.fontStyle,
                            valueAnimation: true,
                            color: textStyle.color,
                        },
                        axisLine: {
                            show: false
                        },
                        axisLabel: {
                            color: '#fff',
                            fontSize: 14,
                            distance: -34,
                        },
                        axisTick: {
                            splitNumber: 10,
                            show: true,
                            lineStyle: {
                                color: '#ccc',
                                width: 1
                            },
                            length: -15,
                        },
                        splitLine: {
                            show: true,
                            length: -25,
                            lineStyle: {
                                color: '#ccc',
                                width: 1
                            }
                        },
                        itemStyle: {
                            normal: {
                                color: '#fff'
                            }
                        },
                        pointer: {
                            width: 4,
                            length: '50%',
                        }
                    }]
                };

                this.chart.setOption(option);
            }
            else {
                // 普通样式
                this.chart.setOption({
                    series: [
                        {
                            type: 'gauge',
                            radius: '80%',
                            center: ['50%', '55%'],
                            min: 0,
                            max: maxValue,
                            splitNumber: maxValue,
                            axisLine: {
                                lineStyle: {
                                    width: gugeWidth,
                                    color: gaugeColors
                                }
                            },
                            pointer: {
                                length: '22%',
                                width: '5%',
                                offsetCenter: [0, '-50%'],
                                itemStyle: {
                                    color: 'auto'
                                }
                            },
                            axisTick: {
                                show: false
                            },
                            splitLine: {
                                show: false,
                                length: 20,
                                lineStyle: {
                                    color: 'auto',
                                    width: 5
                                }
                            },
                            axisLabel: {
                                show: showsize,
                                color: color,
                                fontSize: 14,
                                distance: kdsize,
                                formatter: function (value) {
                                    if (statusData.indexOf(value) >= 0) {
                                        return value;
                                    }

                                    if (value > 0 && value < maxValue) {
                                        return "";
                                    }
                                    return value;
                                }
                            },
                            // title: {
                            //     offsetCenter: [0, '-20%'],
                            //     fontSize: fontSize + "px",
                            //     color: titleColor,
                            //     fontWeight,
                            //     fontStyle
                            // },
                            detail: {
                                fontSize: textStyle.fontSize,
                                fontWeight: textStyle.fontWeight,
                                fontStyle: textStyle.fontStyle,
                                offsetCenter: [0, '0%'],
                                valueAnimation: true,
                                formatter: function (value2) {
                                    // alert(value)
                                    return value;
                                },
                                color: textStyle.color,
                                // backgroundColor: "#ffffff",
                                // borderRadius: [50, 50],
                                // width:100,
                                // height:100,
                                // shadowColor: "#6f6f6f",
                                // shadowBlur: 2,
                            },
                            data: [
                                {
                                    value: value,
                                    // name: title,
                                }
                            ],
                            // anchor: {
                            //     show: true,
                            //     showAbove: true,
                            //     size: "auto",
                            //     itemStyle: {
                            //         borderWidth: 1
                            //     }
                            // },
                        }
                    ]
                })
            }
        },
        getFirstData() {
            if (this.obj.tableData.tableId && this.obj.tableData.itemId) {
                var result = this.getTableValue(this.obj.tableData.tableId, this.obj.tableData.itemId, 1);
                if (result.code == 200) {
                    this.getLineData();
                } else {
                    var self = this;
                    window.setTimeout(function () {
                        self.getFirstData();
                    }, 500);
                }
            }

            // #region 没有配置数据显示默认内容
            if (!this.obj.tableData.tableId) {
                this.showContent = true;
                this.dataValue = 0;
                this.setOptions();
                return false;
            }
            // #endregion

            // #region 参数不完整
            if (!this.obj.tableData.itemId || this.obj.tableData.maxNumber <= 0) {
                this.showContent = false;
                return false;
            }
            // #endregion
        },
        getLineData() {
            var result = this.getTableValue(this.obj.tableData.tableId, this.obj.tableData.itemId, 1);
            if (result.code == 200) {
                var value = result.data;
                this.showContent = true;
                if (this.obj.tableData.decimal >= 0) {
                    value = Number(value).toFixed(this.obj.tableData.decimal);
                }
                this.dataValue = value;
                this.setOptions();
            }
            return false;

            if (this.obj.tableData.tableId && this.obj.tableData.itemId) {
                this.filterForm.tableId = this.obj.tableData.tableId;
                this.filterForm.structureId = this.obj.tableData.itemId;

                if (this.obj.tableData.type != 1) {
                    oneLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var value = res.data.data;

                            this.showContent = true;
                            if (this.obj.tableData.decimal >= 0) {
                                value = Number(value).toFixed(this.obj.tableData.decimal);
                            }
                            this.dataValue = value;
                            this.setOptions();
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                } else {
                    boardOneLoad(this.filterForm).then((res) => {
                        if (res.data.code == 0) {
                            var value = res.data.data;

                            this.showContent = true;
                            if (this.obj.tableData.decimal >= 0) {
                                value = Number(value).toFixed(this.obj.tableData.decimal);
                            }
                            this.dataValue = value;
                            this.setOptions();
                        } else {
                            console.error(res.data.message)
                        }
                    }).catch(() => {
                        clearInterval(this.timer)
                    });
                }
            }
        },
    },
    watch: {
        obj: {
            handler(newVal, oldVal) {
                this.setStyle();

                // // 数据改变了 动态更新echart
                if (JSON.stringify(this.obj.tableData) != this.dataStr) {
                    this.dataStr = JSON.stringify(this.obj.tableData);

                    this.reloadInfo();
                } else {
                    this.setOptions();
                }
            },
            deep: true,  // 深度监听
        }
    },
}
</script>